<template>
  <div class="doc-wrapper">
    <Card :dis-hover="true">
      <Card :dis-hover="true" style="padding:10px;margin-bottom:20px;">
        <!-- 搜索框 -->
        <Form :model="formSearch" ref="formInlineEdit" :rules="ruleInline" label-position="right" label-colon :label-width="85">
          <Row :gutter="10">
            <Col :xs="24" :sm="24" :md="24" :lg="24">
              <FormItem label="代码地址" prop="path">
                <Input clearable v-model="formSearch.path" placeholder="请输入代码地址"/>
              </FormItem>
            </Col>
            <Col :xs="24" :sm="24" :md="12" :lg="6">
              <FormItem label="代码分支" prop="branch">
                <Input clearable v-model="formSearch.branch" placeholder="请输入代码分支"/>
              </FormItem>
            </Col>
            <Col :xs="24" :sm="24" :md="12" :lg="6">
              <FormItem label="用户名" prop="username">
                <Input clearable v-model="formSearch.username" placeholder="请输入用户名"/>
              </FormItem>
            </Col>
            <Col :xs="24" :sm="24" :md="12" :lg="6">
              <FormItem label="密码" prop="password">
                <Input password type="password" v-model="formSearch.password" placeholder="请输入密码"/>
              </FormItem>
            </Col>
            <Col :xs="24" :sm="24" :md="12" :lg="6">
              <FormItem label="端口" prop="port">
                <Input clearable v-model="formSearch.port" placeholder="运行端口"/>
              </FormItem>
            </Col>
            <Col :xs="24" :sm="24" :md="24" :lg="24" style="text-align: right">
              <Button type="primary" @click="exec" shape="circle">构建项目</Button>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card :dis-hover="true" style="padding:0px;margin-bottom:20px;text-align: left;">
        <p style="margin-bottom: 20px;">当前正在进行第 {{ current + 1 }} 步</p>
        <Steps :current="current" :status="status" style="margin-bottom: 20px;">
          <Step title="源码构建" :content="step1"></Step>
          <Step title="代码编译" :content="step2"></Step>
          <Step title="代码部署" :content="step3"></Step>
          <Step title="部署完成" :content="step4"></Step>
        </Steps>
      </Card>

      <div ref="msgBox" style="margin-bottom:20px;text-align: left;
           color: white; border-radius: 3px;
           height: 400px;background-color:black;
           overflow: scroll; padding: 10px;">
        <p v-for="(item,i) in message" :key="i">{{item}}</p>
      </div>

    </Card>
  </div>
</template>

<script>
import {getCode,build,deploy,docker} from '@/api/deploy'

export default {
  name: 'Deploy',
  data(){
    return {
      formSearch: {
        path: localStorage.getItem("path"),
        branch: localStorage.getItem("branch"),
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password"),
        port: localStorage.getItem("port")
      },
      ruleInline: {
        path: [
          { required: true, message: '代码地址不能为空'}
        ],
        branch: [
          { required: true, message: '代码分支不能为空'}
        ],
        username: [
          { required: true, message: '用户名不能为空'}
        ],
        password: [
          { required: true, message: '密码不能为空'}
        ],
        port: [
          { required: true, message: '端口不能为空'}
        ]
      },
      current: 0,
      status: 'wait',
      step1: '准备最新的源代码',
      step2: '等待编译源代码',
      step3: '等待代码打包docker镜像，并部署到服务器',
      step4: '等待代码部署',
      message: [],
      name: '',
      websock: null,
    }
  },
  methods:{
    exec(){
      console.log(this.formSearch);
      localStorage.setItem("path", this.formSearch.path);
      localStorage.setItem("branch", this.formSearch.branch);
      localStorage.setItem("username", this.formSearch.username);
      localStorage.setItem("password", this.formSearch.password);
      localStorage.setItem("port", this.formSearch.port);
      this.$refs['formInlineEdit'].validate((valid) => {
        if(valid){
          this.message = [];
          let date = this.dateFtt("yyyy-MM-dd hh:mm:ss",new Date());
          this.message.push(date + " 执行拉取最新源代码");
          setTimeout(()=>{
            getCode(
              this.formSearch.path,
              this.formSearch.branch,
              this.formSearch.username,
              this.formSearch.password
            ).then(res =>{
              if(res.data.status == 1){
                localStorage.setItem("name",res.data.name);
                this.name = res.data.name;
                this.current = 1;
                this.step1 = res.data.message + " 版本号：" + res.data.version;
                let date = this.dateFtt("yyyy-MM-dd hh:mm:ss",new Date());
                this.message.push(date + " 项目名称:" + res.data.name + " 分支:" + res.data.branch + " 版本:" + res.data.version);
                setTimeout(()=>{
                  if(this.websock == null || this.websock == undefined || this.websock == ''){
                    this.initWebSocket();
                  }
                  this.buildCode();
                }, 2000);
              }else{
                this.current = 0;
                this.status = "error";
                this.step1 = res.data.message;
              }
            })
          }, 2000);
        }
      })
    },
    dateFtt(fmt,date) {
      let o = { 
        "M+" : date.getMonth()+1,     //月份 
        "d+" : date.getDate(),     //日 
        "h+" : date.getHours(),     //小时 
        "m+" : date.getMinutes(),     //分 
        "s+" : date.getSeconds(),     //秒 
        "q+" : Math.floor((date.getMonth()+3)/3), //季度 
        "S" : date.getMilliseconds()    //毫秒 
      }; 
      if(/(y+)/.test(fmt)){
        fmt = fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
      }  
      for(var k in o){
        if(new RegExp("("+ k +")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
      } 
      return fmt; 
    },
    initWebSocket(){ //初始化weosocket
      const wsuri = "wss://tpshion.cn/ci-ws/ws/" + this.name;
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen(){ //连接建立之后执行send方法发送数据
      let actions = {"test":"12345"};
      this.websocketsend(JSON.stringify(actions));
    },
    websocketonerror(){//连接建立失败重连
      this.initWebSocket();
    },
    websocketonmessage(e){ //数据接收
      this.message.push(e.data);
      this.$refs.msgBox.scrollTop = this.$refs.msgBox.scrollHeight
    },
    websocketsend(Data){//数据发送
      this.websock.send(Data);
    },
    websocketclose(e){  //关闭
      console.log('断开连接',e);
    },
    buildCode(){
      build(this.name,this.name).then(res => {
        if(res.data.status == 1){
          this.current = 2;
          this.step2 = res.data.message;
          setTimeout(()=>{
            this.deployCode();
          },2000);
        }else{
          this.status = "error";
          this.step2 = res.data.message;
        }  
      })
    },
    deployCode(){
      deploy(
        this.name,
        this.name,
        ""
      ).then(res => {
        if(res.data.status == 1){
          this.current = 3;
          this.step3 = res.data.message
          setTimeout(()=> {
            this.dockerOps();
          }, 3000);
        }else{
          this.current = 2;
          this.status = "error";
          this.step3 = res.data.message;
        }
      })
    },
    dockerOps(){
      let imageName = "116.63.132.188:5000/" + this.name + ":1.0.0";
      docker(this.name,this.name,imageName,this.formSearch.port).then(res => {
        if(res.data.status == 1){
          this.current = 3;
          this.step4 = res.data.message;
          this.status = "finish";
        }else{
          this.current = 3;
          this.status = "error";
          this.step4 = res.data.message
        }
      })
    }
  },
  created() {
    console.log(this.name)
    this.name = localStorage.getItem("name");
    if(this.name != null && this.name != undefined && this.name != ''){
      this.initWebSocket();
    }
    this.formSearch.path = "https://gitee.com/TPSHION/demo.git";
    this.formSearch.branch = "master";
    this.formSearch.username = "tpshion";
    this.formSearch.password = "Chen12138@";
    this.formSearch.port = "8080";
  },
  destroyed() {
    this.websock.close() //离开路由之后断开websocket连接
  },
}
</script>

<style lang="less" scoped>
.doc-wrapper{
  text-align: center;
}
</style>
